package com.app.couponsharelife.ui.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.WindowManager
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.ToastUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.dialog_sx_bindphone.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.util.concurrent.TimeUnit

/**
 *Created by xct on 2019/4/4
 *Description:购买首席绑定手机号
 */
class SXBindingPhoneDialog(context: Context, themeResId: Int, private val listener: OnClickListener): Dialog(context,themeResId)  {
    private var disposable: Disposable? = null

    private var countDownNum: Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_sx_bindphone)
        initView()
    }
    private fun initView(){
        bindPhoneDialog_tvBinding.setOnClickListener {
            bindingPhone()
        }
        bindPhoneDialog_tvCodeBut.setOnClickListener {
            val phone=bindPhoneDialog_editphone.text.toString().trim()
            if (phone.isEmpty()){
                ToastUtil.getInstance().showToast("请输入手机号")
                return@setOnClickListener
            }
            if (phone.length<11){
                ToastUtil.getInstance().showToast("请输入正确的手机号")
                return@setOnClickListener
            }
            if (!AppUtils.isMobile(phone)){
                ToastUtil.getInstance().showToast("请输入正确的手机号")
                return@setOnClickListener
            }
            sendCode(phone)
        }
        bindPhoneDialog_ivDelete.setOnClickListener {
            bindPhoneDialog_editphone.setText("")
        }
        this.setOnDismissListener {
            if (disposable != null && !disposable!!.isDisposed) {
                disposable?.dispose()
                disposable == null
            }
        }
        window!!.setWindowAnimations(R.style.scale_in_alpha_out)
        setCanceledOnTouchOutside(true)
        //setCancelable(false)
        val lp = window!!.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = lp
    }
    private fun sendCode(mobile:String){
        val map=HashMap<String,String>()
        map["mobile"]=mobile
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.sendCheckCode(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<Any>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<Any>) {
                        if (it.code == 200) {
                            sendCheckCodeSuccess()
                        } else {
                            ToastUtil.getInstance().showToast("发送失败")
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            ToastUtil.getInstance().showToast(e.msg)
                        }
                    }

                })
    }
    private fun bindingPhone(){
        val phone=bindPhoneDialog_editphone.text.toString().trim()
        val code=bindPhoneDialog_editCode.text.toString().trim()
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.getInstance().showToast("请输入手机号")
            return
        }
        if (!AppUtils.isMobile(phone)){
            ToastUtil.getInstance().showToast("请输入正确的手机号")
            return
        }
        if (TextUtils.isEmpty(code)) {
            ToastUtil.getInstance().showToast("请输入验证码")
            return
        }
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["mobile"] = phone
        map["code"] = code
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.updateUser(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<Any>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<Any>) {
                        if (200==it.code){
                            AppUtils.setString(Contacts.USER_MOBILE,phone)
                            listener.click(0,"")
                            dismiss()
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            ToastUtil.getInstance().showToast(e.msg)
                        }else{
                            ToastUtil.getInstance().showToast("网络加载出错")
                        }
                    }
                })
    }
    private fun sendCheckCodeSuccess() {
        countDownNum = 59
        bindPhoneDialog_tvCodeBut.isClickable = false
        bindPhoneDialog_tvCodeBut.setTextColor(context.resources.getColor(R.color.gray_cc))
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)//10s 倒计时
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ _ ->
                    if (countDownNum < 0)
                        goAhead()
                    else {
                        bindPhoneDialog_tvCodeBut.text = "${countDownNum}s后重发"
                        countDownNum--
                    }
                }) { goAhead() }
    }
    private fun goAhead() {
        bindPhoneDialog_tvCodeBut.isClickable = true
        bindPhoneDialog_tvCodeBut.text="获取验证码"
        bindPhoneDialog_tvCodeBut.setTextColor(context.resources.getColor(R.color.black))
        disposable?.dispose()
        disposable == null
    }
}